package com.zq.assistant.func.okhttp.download;

import android.text.TextUtils;
import android.util.Log;

import com.squareup.okhttp.Callback;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;
import com.zq.assistant.func.okhttp.FileTransferListener;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * Created by zhangqiang on 17-6-6.
 */

public class FileDownloadCallback implements Callback {

    private String savePath;
    private FileTransferListener fileTransferListener;

    public FileDownloadCallback(String savePath, FileTransferListener fileTransferListener) {
        this.savePath = savePath;
        this.fileTransferListener = fileTransferListener;
    }

    @Override
    public void onFailure(Request request, IOException e) {

        if (fileTransferListener != null) {
            fileTransferListener.onFinish(request.urlString());
        }
    }

    @Override
    public void onResponse(Response response) {

        try {
            if (response.isSuccessful()) {

                String fileName = getFileName(response);

                File dir = new File(savePath);
                if (!dir.exists() && !dir.mkdirs()) {

                    if (fileTransferListener != null) {
                        fileTransferListener.onFinish(response.request().urlString());
                    }
                    return;
                }
                File saveFile = new File(dir,fileName);

                FileOutputStream fos = new FileOutputStream(saveFile);

                InputStream is = response.body().byteStream();
                byte[] buffer = new byte[1024 * 4];
                int len;
                while ((len = is.read(buffer)) != -1) {

                    fos.write(buffer, 0, len);
                }
                is.close();
                fos.flush();
                fos.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (fileTransferListener != null) {
                fileTransferListener.onFinish(response.request().urlString());
            }
        }
    }

    private String getFileName(Response response){

        String content_disposition = response.header("content-disposition");
        if(TextUtils.isEmpty(content_disposition)){
            return System.currentTimeMillis()+"";
        }
        String[] items = content_disposition.split(";");

        for (String item:
             items) {

            if(item.startsWith("filename=")){

                return item.substring(9);
            }
        }
        return System.currentTimeMillis()+"";
    }
}
